﻿using B.S.Outsourcing.Domain;
using B.S.Outsourcing.ErrorCode;
using B.S.Outsourcing.Infatructrue;
using B.S.Outsourcing.Read.Api.Application.Command.OutsourcingMaterialReleaseOrderModel;
using MediatR;
using NPOI.POIFS.FileSystem;

namespace B.S.Outsourcing.Read.Api.Application.CommandHandler.OutsourcingMaterialReleaseOrderModel
{
    public class QueryOutSourReleaseOrderAllCommandHandler : IRequestHandler<QueryOutSourReleaseOrderAllCommand, ApiPaging<OutsourcingMaterialReleaseOrder>>
    {
        private readonly IBaseRepository<OutsourcingMaterialReleaseOrder> baseRepository;
        private readonly DBHelper1 dBHelper;

        public QueryOutSourReleaseOrderAllCommandHandler(IBaseRepository<OutsourcingMaterialReleaseOrder> baseRepository, DBHelper1 dBHelper)
        {
            this.baseRepository = baseRepository;
            this.dBHelper = dBHelper;
        }

        public async Task<ApiPaging<OutsourcingMaterialReleaseOrder>> Handle(QueryOutSourReleaseOrderAllCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<OutsourcingMaterialReleaseOrder> result = new ApiPaging<OutsourcingMaterialReleaseOrder>();
            var model = $"select * from OutsourcingMaterialReleaseOrderModel where IsDelete=0";
            if (!string.IsNullOrEmpty(request.DocumentCode))
            {
                model += $"and DocumentCode=={request.DocumentCode}";
            }
            if (!string.IsNullOrEmpty(request.MaterialCode))
            {
                model += $"and MaterialCode=={request.MaterialCode}";
            }
            if (!string.IsNullOrEmpty(request.FollowOrderNumber))
            {
                model += $"and FollowOrderNumber=={request.FollowOrderNumber}";
            }
            if (!string.IsNullOrEmpty(request.MaterialName))
            {
                model += $"and MaterialName=={request.MaterialName}";
            }
            if (request.BeginTime!=null)
            {
                model += $"and BeginTime>={request.BeginTime}";
            }
            if (request.EndTime != null)
            {
                model += $"and EndTime<={request.EndTime}";
            }
            var sql = $"{model} order by OutsourcingMaterialReleaseOrderModel.Id offset(({request.pageindex - 1})*{request.pagesize}) rows fetch next {request.pagesize} rows only";
            result.list = dBHelper.GetList<OutsourcingMaterialReleaseOrder>(sql);
            result.Totalcount = result.list.Count();
            result.Totalpage = (int)Math.Ceiling(result.Totalcount * 1.0 / request.pagesize);
            return await Task.FromResult(result);
        }
    }
}
